package health_system.health_system.websocket;

import health_system.health_system.websocket.Server.NettyMediaCommunicationServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Netty WebSocket服务器配置类
 * 负责在Spring应用启动后启动Netty WebSocket服务器
 */
@Configuration
public class NettyMediaCommunicationServerConfig {
    private static final Logger logger = Logger.getLogger(NettyMediaCommunicationServerConfig.class.getName());
    
    @Autowired
    private NettyMediaCommunicationServer nettyMediaCommunicationServer;
    
    private ExecutorService executorService;
    
    /**
     * 应用程序准备就绪后启动Netty WebSocket服务器
     */
    @EventListener(ApplicationReadyEvent.class)
    public void startNettyWebSocketServer() {
        executorService = Executors.newSingleThreadExecutor();
        executorService.submit(() -> {
            try {
                logger.info("启动Netty WebSocket服务器...");
                nettyMediaCommunicationServer.start();
            } catch (Exception e) {
                logger.log(Level.SEVERE, "启动Netty WebSocket服务器失败", e);
            }
        });
    }
    
    /**
     * 应用关闭时关闭Netty WebSocket服务器
     */
    public void shutdown() {
        if (nettyMediaCommunicationServer != null) {
            nettyMediaCommunicationServer.shutdown();
        }
        
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdownNow();
        }
    }
} 